package org.softmed.rest.generation.uri;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.softmed.persistence.PersistenceManager;
import org.softmed.reflection.utils.FieldInfo;
import org.softmed.reflection.utils.ReflectionUtil;

public class URIBuilder {

	Map<String, String> classAppURIs = new HashMap<String, String>();
	Map<String, String> classRelativeURIs = new HashMap<String, String>();
	static String mainPath;
	ReflectionUtil util = new ReflectionUtil();

	private Object getFieldValue(Object obj, Class type, FieldInfo fieldInfo)
			throws Throwable {
		return fieldInfo.getGetter().invoke(obj, null);
	}

	public String getRelativeURIAndId(PersistenceManager odbUtil, Object object)
			throws Throwable {
		Class type = object.getClass();
		String relativePath = classRelativeURIs.get(type.getCanonicalName());

		if (relativePath == null)
			return null;

		FieldInfo pkey = odbUtil.getPrimaryKeyInfo(type);

		if (pkey != null) {
			Object value = pkey.getGetter().invoke(object, null);
			return relativePath + "/" + value;
		}

		long id = odbUtil.getInternalId(object);
		return relativePath + "/" + id;

	}

	public String getFullPath(Class type) throws Throwable {
		return mainPath + classAppURIs.get(type.getCanonicalName())
				+ getRelativeURI(type);
	}

	public String getFullPathAndId(PersistenceManager odbUtil, Object object)
			throws Throwable {
		String relative = getRelativeURIAndId(odbUtil, object);
		if (relative == null)
			return null;
		String uri = mainPath + classAppURIs.get(object.getClass().getCanonicalName()) + relative;
		// return uri.replace("//", "/");
		return uri;
	}

	public String getRelativeURI(Class type) throws Throwable {
		String relativePath = classRelativeURIs.get(type.getCanonicalName());
		return relativePath;
	}

	public Map<String, String> getClassRelativeURIs() {
		return classRelativeURIs;
	}

	public static String getMainPath() {
		return mainPath;
	}

	public static void setMainPath(String mainPath) {
		URIBuilder.mainPath = mainPath;
	}

	public Map<String, String> getClassAppURIs() {
		return classAppURIs;
	}

	public void setClassAppURIs(Map<String, String> classAppURIs) {
		this.classAppURIs = classAppURIs;
	}

}
